#include "eeprom.h"

/*EEPROM data graph
0x2000: remaing count
e.g.: (xx -> don't care)
FF FF FF 00 -> 3 remaining tries
FF FF 00 xx -> 2 remaining tries
...
00 xx xx xx -> access blocked

0x2020: password length + password
e.g.:
03 00 00 00 -> password length = 3, password = 000
01 01 xx xx -> password length = 1, password = 1
00 xx xx xx -> no password (pressing OK directly unlock)
*/

//STC EEPROM(Fake) regs
sfr IAP_DATA	= 0xE2;
sfr IAP_ADDRH	= 0xE3;
sfr IAP_ADDRL	= 0xE4;
sfr IAP_CMD		= 0xE5;
sfr IAP_TRIG	= 0xE6;
sfr IAP_CONTR	= 0xE7;

#define CMD_IDLE	0
#define CMD_READ	1
#define CMD_PROGRAM	2
#define CMD_ERASE	3

#define ENABLE_IAP 0x81

//具体参考STC89C52手册

//擦除一页（写为0xFF）
bool EEP_Erase(uint8_t page) {
	IAP_CONTR = ENABLE_IAP;
	IAP_CMD = CMD_ERASE;
	IAP_ADDRH = page;
	IAP_TRIG = 0x46;
	IAP_TRIG = 0xB9;
	IAP_CONTR = 0;
	IAP_CMD = CMD_IDLE;
	return true;
}

//编程一个字节（0xFF->任意值）
bool EEP_Program(uint16_t addr, uint8_t dat) {
	IAP_CONTR = ENABLE_IAP;
	IAP_CMD = CMD_PROGRAM;
	IAP_ADDRH = (uint8_t)(addr >> 8);
	IAP_ADDRH = (uint8_t)addr;
	IAP_DATA = dat;
	IAP_TRIG = 0x46;
	IAP_TRIG = 0xB9;
	IAP_CONTR = 0;
	IAP_CMD = CMD_IDLE;
	return true;
}

//读取一个字节
uint8_t EEP_Read(uint16_t addr) {
	uint8_t ret;
	IAP_CONTR = ENABLE_IAP;
	IAP_CMD = CMD_READ;
	IAP_ADDRH = (uint8_t)(addr >> 8);
	IAP_ADDRH = (uint8_t)addr;
	IAP_TRIG = 0x46;
	IAP_TRIG = 0xB9;
	ret = IAP_DATA;
	IAP_CONTR = 0;
	IAP_CMD = CMD_IDLE;
	return true;
}


